
package com.sercomm.ott.mediaplayer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.media.AudioAttributes;
import android.media.AudioManager;
//import android.media.MediaMetadata;
import android.media.AudioTrack;
import android.media.MediaActionSound;
import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaExtractor;
import android.media.MediaFormat;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
//import android.os.Handler;
//import android.content.SharedPreference

public class SurfaceViewActivity extends Activity implements MediaPlayer.OnCompletionListener,
        MediaPlayer.OnPreparedListener,MediaPlayer.OnErrorListener, OnBufferingUpdateListener,
        OnClickListener {
	private static final String TAG = "SurfaceView";
    /**
     *
     */
    private SurfaceView surfaceView;

    /**
     * surfaceView
     */
    private SurfaceHolder surfaceHolder;

    /**
     * control seekbar
     */
    private SeekBar seekBar;

    /**
     * play/pause button
     */
    private Button playButton;

    /**
     * replay button
     */
    private Button replayButton;

    /**
     * shotcut button
     */
    private Button screenShotButton;

    /**
     * change screen size button
     */
    private Button videoSizeButton;

    /**
     * load progress bar
     */
    private ProgressBar progressBar;

    /**
     * mediaplayer
     */
    private MediaPlayer mediaPlayer;

    /**
     * record current play position
     */
    private int playPosition = -1;

    /**
     * seekBar auto drag flag
     */
    private boolean seekBarAutoFlag = false;

    /**
     * video time display
     */
    private TextView videoTimeTextView;

    /**
     * total play time
     */
    private String videoTimeString;

    private long videoTimeLong;

    /**
     * video path string
     */
    protected String pathString;

    /**
     * screen width and height
     */
    private int screenWidth, screenHeight;
    /*
     *hide control bar
     */
    private View viewButtonId;
    private View viewSeekbarTime;
    private CountTimeThread mCountTimeThread;
    private final static int HIDE_TIME = 10;
    /*
     * save play pathStrings
     */
    List<String> strings = new ArrayList<String>();

    /*
     * cpuInto view
     */
    private TextView cpuLoading;
    private TextView cpuTemperature;
    private TextView memoryLoading;
    private boolean showCpuInfoFlag = false;
    /*
     * video pathstring view
     */
    private TextView viewVideoPath;
    /*
     * device info view
     */
    private TextView deviceModuleName;
    private TextView deviceSN;
    private TextView deviceEth;
    private TextView deviceMac;
    private boolean showDeviceInfoFlag = false;
    /*
     * video decoded info view
     */
    private TextView videoDecodedWidth;
    private TextView videoDecodedHeight;
    private TextView videoDecodedfps;
    private TextView videoDecodedbps;
    private TextView videoDecodedFrames;
    private TextView videoDroppedFrames;
    private TextView videoErrorFrames;
    private boolean showVideoInfoFlag = false;
    /*
     * audio decoded info view
     */
    private TextView audioDecodedFrames;
    private TextView audioDroppedFrames;
    private TextView audioErrorFrames;
    private boolean showAudioInfoFlag = false;
    private int mVideoWidth = 0;
    private int mVideoHeight = 0;

    /*
     * ethernet receiver
     */
    private BroadcastReceiver myReceiver = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mplayer_surfaceview);
        // get screen width and height
        DisplayMetrics displayMetrics = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        screenWidth = displayMetrics.widthPixels;
        screenHeight = displayMetrics.heightPixels;
        //register network listener


        IntentFilter fliter = new IntentFilter();
        fliter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        myReceiver = new MyReceiver();
        registerReceiver(myReceiver,fliter);

        initALLInfo();

        SystemStatus.initSystemManager(this);
        initViews();

    }

    class MyReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent){
            String action = intent.getAction();
            if(ConnectivityManager.CONNECTIVITY_ACTION.equals(action) && showDeviceInfoFlag){
                if(SystemStatus.isEthernetOn(context)){
                    deviceEth.setText("Ethernet Link  : up"+", "+"linkspeed "+SystemStatus.getEthernetSpeedSM()+
                            ", "+SystemStatus.getEthernetDuplexSM());
                }else {
                    deviceEth.setText("Ethernet Link  : down");
                }
            }
        }
    }
    public void initALLInfo(){
        viewVideoPath = (TextView)findViewById(R.id.view_videopath);
        //initCpuInfo
        showCpuInfoFlag = true;
        cpuLoading = (TextView)findViewById(R.id.cpu_loading);
        cpuTemperature = (TextView)findViewById(R.id.cpu_temperature);
        memoryLoading = (TextView)findViewById(R.id.mem_loading);
        //initDeviceInfo
        deviceModuleName = (TextView)findViewById(R.id.deviceinfo_modulename);
        deviceSN = (TextView)findViewById(R.id.deviceinfo_sn);
        deviceEth = (TextView)findViewById(R.id.deviceinfo_eth);
        deviceMac = (TextView)findViewById(R.id.deviceinfo_mac);
        showDeviceInfoFlag = true;
        //initVideoInfo
        videoDecodedWidth = (TextView)findViewById(R.id.videoinfo_decoded_width);
        videoDecodedHeight = (TextView)findViewById(R.id.videoinfo_decoded_height);
        videoDecodedfps = (TextView)findViewById(R.id.videoinfo_decoded_fps);
        videoDecodedbps = (TextView)findViewById(R.id.videoinfo_decoded_bps);
        videoDecodedFrames = (TextView)findViewById(R.id.videoinfo_decoded_frames);
        videoDroppedFrames = (TextView)findViewById(R.id.videoinfo_dropped_frames);
        videoErrorFrames = (TextView)findViewById(R.id.videoinfo_errors_frames);
        showVideoInfoFlag = true;
        //initAudioInfo
        audioDecodedFrames = (TextView)findViewById(R.id.audioinfo_decoded_frames);
        audioDroppedFrames = (TextView)findViewById(R.id.audioinfo_dropped_frames);
        audioErrorFrames = (TextView)findViewById(R.id.audioinfo_errors_frames);
        showAudioInfoFlag = true;

    }

    public void initViews() {
	    pathString = getIntent().getStringExtra("imFlowsUrlStr");
	    if(pathString == null){
		    pathString = "/sdcard/Movies/1.mp4" ;
	    }

        viewVideoPath.setText(pathString);
        // initialization video control
        viewButtonId=findViewById(R.id.button_id);
        viewSeekbarTime=findViewById(R.id.seekbar_time);
        surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        seekBar = (SeekBar) findViewById(R.id.seekbar);
        playButton = (Button) findViewById(R.id.button_play);
        replayButton = (Button) findViewById(R.id.button_replay);
        videoTimeTextView = (TextView) findViewById(R.id.textView_showTime);
        screenShotButton = (Button) findViewById(R.id.button_screenShot);
        videoSizeButton = (Button) findViewById(R.id.button_videoSize);
        // surfaceHolder
        surfaceHolder = surfaceView.getHolder();
        // set Holder tyoe,this type means surfaceView not manage buffer itself
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        
        // set surface callback
        surfaceHolder.addCallback(new SurfaceCallback());

        getPlayPosition();
        getPathString();
        startCountTimeThread();
    }

    private void startCountTimeThread(){
        mCountTimeThread = new CountTimeThread(HIDE_TIME);
        mCountTimeThread.start();
    }

    // SurfaceView callBack
    private class SurfaceCallback implements SurfaceHolder.Callback {
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
		//LogUtil.d(TAG,"SurfaceCallback");
        }

        public void surfaceCreated(SurfaceHolder holder) {
            // create surfaceView
            // set video resources
            LogUtil.d(TAG,"surfacecreate" );
            playVideo();
        }

        public void surfaceDestroyed(SurfaceHolder holder) {
            // destory surfaceView and mediaPlayer
            LogUtil.d(TAG,"surfaceDestoryed");
            surfaceHolder = null;
            if (null != mediaPlayer) {
                mediaPlayer.reset();
                mediaPlayer.release();
                mediaPlayer = null;
            }

        }

    }

    /**
     * play video
     */
    public void playVideo() {
        // inital MediaPlayer
        mediaPlayer = new MediaPlayer();
        // reset mediaPalyer
        mediaPlayer.reset();
        // audio type
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        // play complete monitor
        mediaPlayer.setOnCompletionListener(this);
        // video load complete monitor
        mediaPlayer.setOnPreparedListener(this);
        // error monitor callback
        mediaPlayer.setOnErrorListener(this);
        // cache change monitor
        mediaPlayer.setOnBufferingUpdateListener(this);
//        Uri uri = Uri.parse("http://192.168.1.2/davis/1.wmv");
        try {
            // mediaPlayer.reset();
            mediaPlayer.setDataSource(pathString);

            // mediaPlayer.setDataSource(this, uri);
            // mediaPlayer.setDataSource(SurfaceViewActivity.this, uri);
            // asynchronous load video
            mediaPlayer.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "load video error！", Toast.LENGTH_LONG).show();
        }

        //String a = am.getParameters()
    }

    /**
     * video load complete callback
     */
    @Override
    public void onPrepared(MediaPlayer mp) {
        LogUtil.d(TAG,"onPrepared");
        // when video load complete ,hide progressbar
        progressBar.setVisibility(View.GONE);
        // seekto saved playposition
        LogUtil.d(TAG,"oprepared playerposition is "+playPosition);
        if (playPosition >= 0) {
            mediaPlayer.seekTo(playPosition);
            //playPosition = -1;
            // surfaceHolder.unlockCanvasAndPost(Constants.getCanvas());
        }
        seekBarAutoFlag = true;
        // set seekbar
        seekBar.setMax(mediaPlayer.getDuration());
        videoTimeLong = mediaPlayer.getDuration();
        videoTimeString = getShowTime(videoTimeLong);
        LogUtil.d(TAG,"videoTimeLong ="+videoTimeLong+"videoTimeString ="+videoTimeString);
        videoTimeTextView.setText("00:00:00/" + videoTimeString);
        //setCpuInfo();
        seekBar.setOnSeekBarChangeListener(new SeekBarChangeListener());
        //button click monitor
        replayButton.setOnClickListener(SurfaceViewActivity.this);

        playButton.setOnClickListener(SurfaceViewActivity.this);

        screenShotButton.setOnClickListener(SurfaceViewActivity.this);

        videoSizeButton.setOnClickListener(SurfaceViewActivity.this);
        // start playing
        mediaPlayer.start();

        mVideoWidth = mp.getVideoWidth();
        mVideoHeight = mp.getVideoHeight();

        LogUtil.d(TAG,"----width height "+mVideoWidth+" "+mVideoHeight);
        if(true || showVideoInfoFlag){
            setFixedVideoView();
        }
        /*
        if(showVideoInfoFlag){
            if(pathString!=null){
                MediaMetadataRetriever mmdr = null;
                try{
                    mmdr = new MediaMetadataRetriever();

                    HashMap<String,String> header = new HashMap<>();
                    mmdr.setDataSource(pathString,header);
                    String a = mmdr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_AUDIO);
                    String v = mmdr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_VIDEO);
                    String bps = mmdr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_BITRATE);
                    String type =mmdr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_CAPTURE_FRAMERATE);
                    String dtime = mmdr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
                    LogUtil.d(TAG,"----frames "+" bps "+bps + "  type "+type +" time "+ dtime+ " hasaudio "+a+"" +
                            " hasvideo "+v);
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    if (mmdr!=null)
                        mmdr.release();
                }
            }
        }
        */


        mediaPlayer.setDisplay(surfaceHolder);
        // refresh seekbar
        new Thread(runnable).start();
        // surfaceView keep on screen
        mediaPlayer.setScreenOnWhilePlaying(true);
        surfaceHolder.setKeepScreenOn(true);

    }


    /**
     * thread of seekbar
     */
    private Runnable runnable = new Runnable() {

        public void run() {

            try {
                while (seekBarAutoFlag) {
                    /*
                     * mediaPlayer is not null and is playing,refresh seekbar
                     */
                    if (null != SurfaceViewActivity.this.mediaPlayer
                            && SurfaceViewActivity.this.mediaPlayer.isPlaying()) {
                        seekBar.setProgress(mediaPlayer.getCurrentPosition());
                    }
                    Thread.sleep(200);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    /**
     * seekBar darg monitor
     *
     */
    @SuppressWarnings("unused")
    private class SeekBarChangeListener implements OnSeekBarChangeListener {
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (progress >= 0) {
                if (fromUser) {
                    mediaPlayer.seekTo(progress);
                }
                // set current playing time
                videoTimeTextView.setText(getShowTime(progress) + "/" + videoTimeString);
            }
        }

        public void onStartTrackingTouch(SeekBar seekBar) {

            LogUtil.d(TAG,"onStartTrackingTouch");

        }

        public void onStopTrackingTouch(SeekBar seekBar) {

            LogUtil.d(TAG,"onStopTrackingTouch");
        }

    }

    /*
     *key down callback
     */
    @Override
    public boolean onKeyDown(int key, KeyEvent event){
        if(key==KeyEvent.KEYCODE_BACK)
            return super.onKeyDown(key,event);
        //if(!mCountTimeThread.isAlive())
        //    mCountTimeThread.start();
        //reset mCountTime and show controlbar
        mCountTimeThread.reset();
        show();
        return false;
    }
    /**
     * button click monitor
     */
    public void onClick(View v) {
        //replay
        if (v == replayButton) {
            LogUtil.d(TAG,"replayButton");
            if (null != mediaPlayer) {
                LogUtil.d(TAG,"null!=mediaPlayer");
                mediaPlayer.seekTo(0);
                seekBar.setProgress(0);
                if (!mediaPlayer.isPlaying()) {
                    mediaPlayer.start();
                }
            } else {
                LogUtil.d(TAG,"null==mediaPlayer");
                playVideo();
            }

        }
        // play/pause
        if (v == playButton) {
            LogUtil.d(TAG,"playButton");
            if (null != mediaPlayer) {
                if (mediaPlayer.isPlaying()) {
                    playPosition = mediaPlayer.getCurrentPosition();
                    // seekBarAutoFlag = false;
                    mediaPlayer.pause();
                    playButton.setText("播放");
                } else {
                    if (playPosition >= 0) {
                        // seekBarAutoFlag = true;
                        mediaPlayer.seekTo(playPosition);
                        mediaPlayer.start();
                        playButton.setText("暂停");
                        playPosition = -1;
                    }
                }

            }
        }
        // shotcut screen
        if (v == screenShotButton) {
            LogUtil.d(TAG,"screenShotButton");
            if (null != mediaPlayer) {
                if (mediaPlayer.isPlaying()) {
                    playPosition = mediaPlayer.getCurrentPosition();
                    mediaPlayer.pause();
                    playButton.setText("播放");
                }
                savaScreenShot(playPosition);
            } else {
                Toast.makeText(SurfaceViewActivity.this, "No playing video！", Toast.LENGTH_SHORT).show();
            }
        }
        //screen size
        if (v == videoSizeButton) {
            LogUtil.d(TAG,"videoSizeButton");
            changeVideoSize();
        }
    }

    /**
     * play complete callback
     *
     */
    @Override
    public void onCompletion(MediaPlayer mp) {
        LogUtil.d(TAG,"onCompletion");

        seekBar.setProgress(Integer.parseInt(String.valueOf(videoTimeLong)));

        seekBarAutoFlag = false;

    }

    /**
     * video buffer monitor,started status call
     */
    public void onBufferingUpdate(MediaPlayer mp, int percent) {

        LogUtil.e("text", "onBufferingUpdate-->" + percent);

    }

    /**
     * error monitor
     */
    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        switch (what) {
            case MediaPlayer.MEDIA_ERROR_UNKNOWN:
                Toast.makeText(this, "MEDIA_ERROR_UNKNOWN", Toast.LENGTH_SHORT).show();
                break;
            case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
                Toast.makeText(this, "MEDIA_ERROR_SERVER_DIED", Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }

        switch (extra) {
            case MediaPlayer.MEDIA_ERROR_IO:
                Toast.makeText(this, "MEDIA_ERROR_IO", Toast.LENGTH_SHORT).show();
                break;
            case MediaPlayer.MEDIA_ERROR_MALFORMED:
                Toast.makeText(this, "MEDIA_ERROR_MALFORMED", Toast.LENGTH_SHORT).show();
                break;
            case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
                Toast.makeText(this, "MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK",
                        Toast.LENGTH_SHORT).show();
                break;
            case MediaPlayer.MEDIA_ERROR_TIMED_OUT:
                Toast.makeText(this, "MEDIA_ERROR_TIMED_OUT", Toast.LENGTH_SHORT).show();
                break;
            case MediaPlayer.MEDIA_ERROR_UNSUPPORTED:
                Toast.makeText(this, "MEDIA_ERROR_UNSUPPORTED", Toast.LENGTH_SHORT).show();
                break;
        }
        return false;
    }


    /*
     * set device info view
     */
    private void setFixedDeviceView(){
        String Mac = SystemStatus.getEthernetMacSM();
        deviceMac.setText("MAC address "+ Mac);
        deviceModuleName.setText("Product name  : "+Build.PRODUCT);
        deviceSN.setText("S/N      : "+Build.SERIAL);
    }
    /*
     * video width and height
     */
    private void setFixedVideoView(){
        videoDecodedWidth.setText("decoded width : "+mVideoWidth);
        videoDecodedHeight.setText("decoded height : "+mVideoHeight);
    }
    /**
     * start from pause
     */
    protected void onResume() {
        LogUtil.d(TAG,"onResume");
        super.onResume();
        if(true || showDeviceInfoFlag){
            setFixedDeviceView();
        }
        if (playPosition >= 0) {

            if (null != mediaPlayer) {
                seekBarAutoFlag = true;
                mediaPlayer.seekTo(playPosition);
                mediaPlayer.start();
            } else {
                playVideo();
            }

        }
    }

    /**
     * pause
     */
    @Override
    protected void onPause() {
        LogUtil.d(TAG,"onPause");
        super.onPause();
        try {
            if (null != mediaPlayer && mediaPlayer.isPlaying()) {
                playPosition = mediaPlayer.getCurrentPosition();
                mediaPlayer.pause();
                seekBarAutoFlag = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * screen rotation call
     * */
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (null != mediaPlayer) {

            playPosition = mediaPlayer.getCurrentPosition();
        }
    }

    /**
     * scrren rotation complete
     */
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

    }
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    /**
     * call when screen destory
     */
    @Override
    protected void onDestroy() {
        LogUtil.d(TAG,"onDestory");
        if(myReceiver != null){
            unregisterReceiver(myReceiver);
            myReceiver = null;
        }
        savePlayPosition();
        savePathString();
        LogUtil.d(TAG,"playPosition is "+ playPosition + "pathstring "+pathString);
        try {
            if (null != SurfaceViewActivity.this.mediaPlayer) {
                // set flag in case of when video stop,thread is still run
                seekBarAutoFlag = false;
                if (mediaPlayer.isPlaying()) {

                    mediaPlayer.stop();
                }
                SurfaceViewActivity.this.mediaPlayer.release();
                SurfaceViewActivity.this.mediaPlayer = null;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }

    /**
     * transformation play time
     *
     * @param milliseconds
     * @return hh:mm:ss or mm:ss
     */
    @SuppressLint("SimpleDateFormat")
    public String getShowTime(long milliseconds) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(milliseconds);
        SimpleDateFormat dateFormat = null;
        // >60min?
        if (milliseconds / 60000 > 60) {
            dateFormat = new SimpleDateFormat("hh:mm:ss");
        } else {
            dateFormat = new SimpleDateFormat("mm:ss");
        }
        return dateFormat.format(calendar.getTime());
    }

    /**
     * save shotcut screen
     *
     * @param  :current playing time
     */
    public void savaScreenShot(long time) {
        LogUtil.d(TAG,"saveScreenShot");
        boolean isSave = false;
        String path = null;
        String fileName = null;
        if (time >= 0) {
            try {
                //Uri uri = Uri
                //        .parse("http://192.168.1.2/davis/1.wmv");
                MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
                mediaMetadataRetriever.setDataSource(pathString,new HashMap<String, String>());
                String timeString = mediaMetadataRetriever
                        .extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
                long timelong = Long.parseLong(timeString) * 1000;
                // current position
                long index = (time * timelong) / mediaPlayer.getDuration();
                Bitmap bitmap = mediaMetadataRetriever.getFrameAtTime(time * 1000,
                        MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
                mediaMetadataRetriever.release();

                String storageState=android.os.Environment.getExternalStorageState();
                LogUtil.d(TAG,"storageState is "+storageState);
                if (storageState.equals(Environment.MEDIA_MOUNTED)) {
                    path = Environment.getExternalStorageDirectory().getAbsolutePath();
                    LogUtil.d(TAG,"external path is "+path);
                } else {
                    path = Environment.getDataDirectory().getAbsolutePath();
                    LogUtil.d(TAG,"internal path is "+path);
                }

                fileName = Calendar.getInstance().getTimeInMillis() + ".jpg";
                LogUtil.d(TAG, "fileName is "+fileName);
                File dir= new File(path+"/shotcut/");
                if(!dir.exists()){
                    dir.mkdir();
                }
                LogUtil.d(TAG,"dir.getAbsolutepath is "+dir.getAbsolutePath());
                File file = new File(dir.getAbsolutePath() + "/"+fileName);

                /*if (!file.exists()) {
                    file.createNewFile();
                }*/
                FileOutputStream fileOutputStream = new FileOutputStream(file);
                bitmap.compress(CompressFormat.JPEG, 100, fileOutputStream);
                isSave = true;
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (isSave) {
                ImageView imageView = new ImageView(this);
                imageView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                        LayoutParams.WRAP_CONTENT));
                imageView.setImageBitmap(BitmapFactory.decodeFile(path + "/shotcut/" + fileName));
                new AlertDialog.Builder(this).setView(imageView).show();
            }
        }

    }

    /**
     * change video size
     */
    public void changeVideoSize() {
        LogUtil.d(TAG,"changeVideoSize");
        String videoSizeString = videoSizeButton.getText().toString();
        int width = mediaPlayer.getVideoWidth();
        int height = mediaPlayer.getVideoHeight();
        LogUtil.d(TAG,"width is "+width+" height is "+height);
        if ("窗口".equals(videoSizeString)) {
            /*
            if (width > screenWidth || height > screenHeight) {
                // width and height multiple
                float vWidth = (float) width / (float) screenWidth;
                float vHeight = (float) height / (float) screenHeight;

                float max = Math.max(vWidth, vHeight);

                width = (int) Math.ceil((float) width / max);
                height = (int) Math.ceil((float) height / max);
            }*/
            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(width/2,
                    height/2);

            layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
            surfaceView.setLayoutParams(layoutParams);
            videoSizeButton.setText("全屏");
        } else if ("全屏".equals(videoSizeString)) {
            // full screen
            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(screenWidth,
                    screenHeight);
            layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
            surfaceView.setLayoutParams(layoutParams);
            videoSizeButton.setText("窗口");
        }
    }


    /*
     *hide control bar function
     */
    private void hide(){
        if(viewSeekbarTime.getVisibility()==View.VISIBLE || viewButtonId.getVisibility()==View.VISIBLE){
            viewButtonId.setVisibility(View.GONE);
            viewSeekbarTime.setVisibility(View.GONE);
        }
    }
    /*
     *show control bar
     */
    private void show(){
        if(viewButtonId.getVisibility()!=View.VISIBLE || viewSeekbarTime.getVisibility()!=View.VISIBLE){
            viewButtonId.setVisibility(View.VISIBLE);
            viewSeekbarTime.setVisibility(View.VISIBLE);
        }
    }
    /*
     * set cpu information
     */
    private void setCpuInfo(){
        //String fmCpuLoad = String.format("%.2f",SystemStatus.getCpuLoading(SurfaceViewActivity.this));

        int fmCpuTemp = SystemStatus.getCpuTemperatureSM();
        //LogUtil.d(TAG,"------cputemp "+fmCpuTemp);
        String fmMenLoad = String.format("%.2f", SystemStatus.getMemoryLoading(SurfaceViewActivity.this));
        cpuTemperature.setText("CPU Temperature :" +String.valueOf(fmCpuTemp));
        memoryLoading.setText("MEM Loading :" + fmMenLoad+"%");
    }
    private void setCpuLoad(int arg1,int arg2){
        //String fmCpuLoad=SystemStatus.getCpuLoading(SurfaceViewActivity.this);

        cpuLoading.setText("CPU Loading :"+arg1+"."+arg2+"%" + "  load:"+SystemStatus.getCpuLoad());
    }
    private void setVideoFrames(int arg1){
        videoDecodedFrames.setText("decoded frames : "+arg1);
    }

    /*
     *  handle
     */
    private final int MSG_HIDE = 0x001;
    private final int MSG_SHOWCPUINFO = 0x002;
    private final int MSG_SHOWCPULOAD = 0x003;
    private final int MSG_SHOWVIDEOFRAMES = 0x004;
    private MyHandler mHandler = new MyHandler(SurfaceViewActivity.this);
    private class MyHandler extends android.os.Handler{
        private WeakReference<SurfaceViewActivity> weakRef;
        public MyHandler(SurfaceViewActivity activity){
            weakRef = new WeakReference<SurfaceViewActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg){
            final SurfaceViewActivity surfaceViewTestActivity = weakRef.get();
            if(surfaceViewTestActivity != null){
                switch (msg.what){
                    case MSG_HIDE:
                        surfaceViewTestActivity.hide();
                       // if(surfaceViewTestActivity.mCountTimeThread.isAlive())
                       //     surfaceViewTestActivity.mCountTimeThread.interrupt();
                        break;
                    case MSG_SHOWCPUINFO:
                        surfaceViewTestActivity.setCpuInfo();
                        break;
                    case MSG_SHOWCPULOAD:
                        surfaceViewTestActivity.setCpuLoad(msg.arg1,msg.arg2);
                        break;
                    case MSG_SHOWVIDEOFRAMES:
                        //surfaceViewTestActivity.setVideoFrames(msg.arg1);

                }
            }

        }
        public void sendHideControlMessage(){
            obtainMessage(MSG_HIDE).sendToTarget();
        }
        //public void sendShowCpuInfoMessage() { obtainMessage(MSG_SHOWCPUINFO).sendToTarget();}
    };
    /*
     * record the time of control bar exit thread
     */
    @SuppressWarnings("unuesd")
    private class CountTimeThread extends Thread{
        private final long maxVisibleTime;
        private long startVisibleTime;
        public CountTimeThread(int second) {
            maxVisibleTime = second * 1000;
            setDaemon(true);
        }
        public synchronized void reset(){
            startVisibleTime = System.currentTimeMillis();
        }

        @Override
        public void run(){
            startVisibleTime = System.currentTimeMillis();

            while(true){
                if((startVisibleTime+maxVisibleTime)<System.currentTimeMillis()){
                    mHandler.sendHideControlMessage();
                    startVisibleTime = System.currentTimeMillis();
                }
                try{
                    Message msgCupInfo = new Message();
                    msgCupInfo.what= MSG_SHOWCPUINFO;
                    mHandler.sendMessage(msgCupInfo);

                    // cpu usage
                    String start = SystemStatus.getCpuLoading();
                    Thread.sleep(1000);
                    String end = SystemStatus.getCpuLoading();
                    double tPercent = 0;
                    try {
                        tPercent = SystemStatus.getCpuLoadPercent(start, end);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    Message msg = new Message();
                    msg.what = MSG_SHOWCPULOAD;
                    msg.arg1 = (int)tPercent;
                    msg.arg2 = (int)(100*(tPercent-msg.arg1));
                    mHandler.sendMessage(msg);

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }



    /*
      *save the playing path and time,it can continue play when next time
      */
    public void savePlayPosition(){
        SharedPreferences.Editor editor = getSharedPreferences("data",MODE_PRIVATE).edit();
        //editor.putInt("playPosition",playPosition);
        //editor.putString("path",pathString);
        editor.putInt(pathString,playPosition);
        editor.commit();

    }
    public void savePathString(){
        SharedPreferences.Editor editor = getSharedPreferences("path",MODE_PRIVATE).edit();
        if(!strings.contains(pathString)){
            strings.add(pathString);
        }
        else{
            updateSortString();
        }
        if(strings.size() > 3){
            LogUtil.d(TAG,"remove " + strings.get(0));
            removeTarget(strings.get(0));
            strings.remove(0);
        }

        LogUtil.d(TAG,"savePathString pathNums "+strings.size());
        editor.putInt("pathNums",strings.size());
        for(int i=0;i<strings.size();i++){
            editor.putString("item"+i,strings.get(i));
            LogUtil.d(TAG,"savepathString "+ i+" "+strings.get(i));
        }
        editor.commit();
    }
    public void updateSortString(){
        int i = strings.indexOf(pathString);
        for(;i<strings.size()-1;){
            String tmp = strings.get(i);
            strings.set(i,strings.get(++i));
            strings.set(i,tmp);
        }
    }
    public void getPathString(){
        SharedPreferences prefPath = getSharedPreferences("path",MODE_PRIVATE);
        int nums = prefPath.getInt("pathNums",0);
        for(int i=0;i<nums;i++){
            String item = prefPath.getString("item"+i,null);
            LogUtil.d(TAG,"getpathstring "+i +" : "+ item);
            strings.add(item);
        }
    }
    public void getPlayPosition(){
        SharedPreferences pref = getSharedPreferences("data",MODE_PRIVATE);
        /*
        String tmpPath = pref.getString("path","");
        LogUtil.d(TAG,"tmpPath is "+tmpPath);
        if(pathString.equals(tmpPath))
            playPosition = pref.getInt("playPosition",0);
        else
            playPosition = -1;
        */
        if(pref.contains(pathString))
            playPosition = pref.getInt(pathString,0);
        else
            playPosition = -1;

        LogUtil.d(TAG,"get playPosition is "+playPosition);
    }
    public void removeTarget(String s){
        SharedPreferences.Editor editorRemove = getSharedPreferences("data",MODE_PRIVATE).edit();
        editorRemove.remove(s);
        editorRemove.commit();
        //editorRemove.clear().commit();
    }

}
